import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-05-13
 * Time: 13:05
 */
public class InsertSort {
    /**
     * 插入排序
     * @param array
     */
   public static void testInsertSort(int[] array) {
        for(int i = 1; i < array.length; i++) {
            int tmp = array[i];
            int j = i - 1;
            for(; j >= 0; j --) {
                if(array[j] > tmp) {
                    array[j + 1] = array[j];
                } else {
                    //array[j + 1] = tmp;
                    break;
                }
            }
            array[j + 1] = tmp;
        }
    }

    /**
     * 插入排序错误示范
     * @param array
     */
    public static void testInsertSort1(int[] array) {
        for(int i = 1; i < array.length; i++) {
            int tmp = array[i];
            for(int j = i - 1; j >= 0; j --) {
                if(array[j] > tmp) {
                    array[j + 1] = array[j];
                } else {
                    array[j + 1] = tmp;
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {5, 4, 3, 2};
        testInsertSort(array);
        for (int x : array) {
            System.out.print(x + " ");
        }
        System.out.println();
        System.out.println(Arrays.toString(array));
        //System.out.println(array);
    }
}
